from flask import request  # 导入Flask的request对象
from datetime import datetime
from email_sender import email_sender  # 导入单例实例
from email_content import feedback_reply_html  # 如需使用HTML模板
import constant
import csv

def get_real_ip():
    """获取真实IP，处理反向代理情况"""
    # 优先从X-Real-IP获取
    real_ip = request.headers.get('X-Real-IP')
    if real_ip:
        return real_ip

    # 其次从X-Forwarded-For获取（可能包含多个IP，取第一个）
    x_forwarded_for = request.headers.get('X-Forwarded-For')
    if x_forwarded_for:
        return x_forwarded_for.split(',')[0].strip()

    # 最后使用默认方法
    return request.remote_addr

def write_to_log(action_str,err=''):
    """
    将字符串内容写入log.txt文件
    :param err:
    :param action_str: 操作
    """
    ip_str = get_real_ip()
    time_str = get_now_time_str()
    if err == '':content = f"[{time_str}] [ip:{ip_str}] [操作：{action_str}]\n"
    else:content = f"[{time_str}] [ip:{ip_str}] [操作：{action_str}]\nerr:{err}\n"
    try:
        # 使用追加模式('a')，编码设置为utf-8以支持中文
        with open('log.txt', 'a', encoding='utf-8') as f:
            # 写入内容，末尾加换行符分隔不同日志
            f.write(f"{content}\n")
        return True
    except Exception as e:
        print(f"写入日志失败: {e}")
        return False


def get_now_time_str(format_str: str = "%Y-%m-%d %H:%M:%S") -> str:
    """
    获取当前时间并转换为指定格式的字符串

    :param format_str: 时间格式字符串，默认值为 "%Y-%m-%d %H:%M:%S"
                       常用格式符：
                       %Y - 四位年份，%m - 两位月份，%d - 两位日期
                       %H - 24小时制小时，%M - 分钟，%S - 秒
    :return: 格式化后的时间字符串
    """
    current_time = datetime.now()
    return current_time.strftime(format_str)

def operation_log(action_str, op):
    if op == 1:
        action_str = action_str + " " + "状态：成功"
    elif op == 0:
        action_str = action_str + " " + "状态：失败"
    else:
        action_str = action_str + " " + "状态：未知"

    return action_str

def send_feedback_notice(to_email, to_subject, to_name, body="这是邮件的文本内容..."):

    # 准备邮件参数
    recipient = to_email  # 收件人邮箱
    subject = to_subject

    # 如需使用HTML模板（示例）
    name = to_name
    feedback_topic = to_subject
    html_content = feedback_reply_html.format(
        name=name,
        feedback_topic=feedback_topic,
        your_email=recipient
    )

    # 调用发送邮件方法
    success = email_sender.send_email(
        to=recipient,
        subject=subject,
        body=body,
        html=html_content  # 可选，如需HTML格式
        # 可选参数：cc="抄送邮箱", bcc="密送邮箱"
    )

    # 处理发送结果
    if success:
        print("邮件发送成功！")
        # 可获取详细结果
        print("发送详情：", email_sender.get_last_result())
        # 日志
        action_str = operation_log(constant.Actions.SEND_FEEDBACK_NOTIFICATIONS.value, 1)
        write_to_log(action_str)
    else:
        print("邮件发送失败！")
        mess = "邮件发送失败原因：" + email_sender.get_last_result()["message"]
        print(mess)
        # 日志
        action_str = operation_log(constant.Actions.SEND_FEEDBACK_NOTIFICATIONS.value, 0)
        write_to_log(action_str,mess)


def notice_csv2dict(file_path):
    all_dict = {}
    with open(file_path, 'r', encoding='utf-8') as csv_file:
        reader = csv.reader(csv_file)
        for row in reader:
            if len(row) == 2:  # 确保每行有两列数据，对应键值对
                key = row[0]
                value = row[1]
                all_dict[key] = value

    # print(all_dict)

    notice_info = {
            "show": all_dict["show"],  # 控制公告是否显示
            "content": all_dict["content"],
            "details": [
                {
                    "title": all_dict["details_title"],
                    "content": all_dict["details_content"],
                    "date": all_dict["details_date"],
                    "type": all_dict["details_type"]   #primary 优先;success 成功;warning 注意;danger/error 紧急;info 常规
                }
            ]
        }

    result_dict = {
        "version_info": all_dict["version_info"],
        "terms_version": all_dict["terms_version"],
        "notice_info": notice_info
    }

    return result_dict

if __name__ == '__main__':
    print(notice_csv2dict(constant.init_data_url).get('version_info'))